<template>
  <div>
    <el-form :model="passwordForm" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input v-model="passwordForm.oldPassword" type="password" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" type="password" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="passwordForm.confirmPassword" type="password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitPassword">提交修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import request from '@/utils/request.js';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();
const formRef = ref(null);
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
  id: null,
  username: ''
});

// 在组件挂载时获取用户信息
const getUserInfo = () => {
  const userInfo = JSON.parse(localStorage.getItem('xm-pro-user'));
  if (userInfo && userInfo.id) {
    passwordForm.value.id = userInfo.id;
    passwordForm.value.username = userInfo.username;
  }
};

getUserInfo();

const rules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
};

const submitPassword = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = {
          id: passwordForm.value.id,
          username: passwordForm.value.username,
          password: passwordForm.value.oldPassword,
          newPassword: passwordForm.value.newPassword
        };
        await request.put('/user/updatePassword', data);
        ElMessage.success('密码修改成功，请重新登录');
        // 清除登录信息
        localStorage.removeItem('xm-pro-user');
        // 延迟跳转到登录页
        setTimeout(() => {
          router.push('/login');
        }, 1500);
      } catch (error) {
        ElMessage.error(error.response?.data?.msg || '密码修改失败，请稍后重试');
      }
    }
  });
};
</script>

<style scoped>
/* 可添加自定义样式 */
</style>